package com.wb.controller;

import com.wb.entity.SaveUserId;
import com.wb.entity.User;
import com.wb.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
@Controller

public class settingController {
    //setting是用户注册账户后主动要修改内容
    @RequestMapping(value="/setting")
    public ModelAndView setting(@RequestParam(value = "userName",required = false)String userName,
                                @RequestParam(value = "sex",required = false)String sex,
                                @RequestParam(value = "birthday",required = false)String birthday,
                                @RequestParam(value = "email",required = false)String email,
                                @RequestParam(value = "introduction",required = false)String introduction,
                                @RequestParam(value = "old_pwd",required = false)String old_pwd,
                                @RequestParam(value = "new_pwd",required = false)String new_pwd,
                                @RequestParam(value = "photo",required = false) MultipartFile file,
                                HttpServletRequest request) throws IOException {
        UserService uservice = new UserService();
        ModelAndView mdv=new ModelAndView();

        //准备用户名称和头像
        if(SaveUserId.userId==0) {
            mdv.addObject("photo", "/picture/user1.png");
            mdv.addObject("name", "匿名");
            mdv.addObject("result","至少输入旧密码以便更改信息！");
            mdv.setViewName("setting");
            return mdv;
        }
        else {
            User user = uservice.userMessage(SaveUserId.userId);
            mdv.addObject("photo", user.getPhoto());
            mdv.addObject("name", user.getUser_name());
        }
        System.out.println(userName+file);
        System.out.println("我是图片"+file);
        System.out.println(userName+sex+birthday+email);

        LocalDate date;
        mdv.setViewName("setting");
        //直接获取，以免为空

        User user=uservice.userMessage(SaveUserId.userId);
        if(user==null)//防止空指针
            user=new User();
        if(file!=null)
        {
            //      获取Servlet的运行路径下的imgs文件夹作为上传图片的存储路径
            String uploadRootPath = "C:/picture/";
            System.out.println("uploadRootPath="+uploadRootPath);

//      检查图片存储路径是否存在，如果不存在，创建路径
            File uploadRootDir = new File(uploadRootPath);
            if(!uploadRootDir.exists())
                uploadRootDir.mkdirs();
//      获取源文件的文件名
            String fileName = file.getOriginalFilename();

//      创建目标文件，制定文件存储路径和文件名
            File targetFile = new File(uploadRootPath+ fileName);
            if(fileName!=null&&fileName.length()>0){
                try {
//              将源文件转移到目标文件，使用transferTo方法
                    file.transferTo(targetFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
//      由于获取到的User对象没有userphoto属性，这里补全
            System.out.println("fileDir="+uploadRootPath+fileName);
            user.setPhoto("picture/"+fileName);
            System.out.println("图片已保存！！！！！！！！！！！！！！！！！！");
        }
        //对生日等数据进行赋值
        if(birthday!=null)
        {
            DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate day = LocalDate.parse(birthday, format);
            user.setBirthday(day);
        }

        char sex_written='f';
        if(sex!=null)//首次打开会是null
        {
            System.out.println(sex);
            if(sex.equals("男"))
                sex_written='m';
            else
                sex_written='f';
            user.setSex(sex_written);
        }
        if(introduction!=null)
        {
            user.setIntroduction(introduction);
        }
        if(email!=null)
        {
            user.setEmail(email);
        }
        if(userName!=null)
        {
            user.setUser_name(userName);
        }
        if(new_pwd!=null)
        {
            user.setUser_password(new_pwd);
        }

//
        if(old_pwd!=null) //至少输入一个旧密码才能修改
        {
            String result=uservice.userSetting(user,old_pwd);
            if(result.equals("old password is wrong"))
            {
                mdv.setViewName("setting");
                mdv.addObject("result","旧密码错误！");
            }
            else if(result.equals("failed"))
            {
                mdv.setViewName("setting");
                mdv.addObject("result","保存失败！");
            }
            else
            {
                System.out.println("succeed in update!");
                mdv.setViewName("redirect:setting");
                mdv.addObject("result","保存成功！");
                return mdv;
            }

            if(user!=null)//       保存失败给用户返回数据库原有的值
            {
                mdv.addObject("username",user.getUser_name());
                if(user.getIntroduction()!=null)
                    mdv.addObject("introduction",user.getIntroduction());
                if(user.getEmail()!=null)
                    mdv.addObject("email",user.getEmail());
                if(user.getBirthday()!=null)
                    mdv.addObject("birthday",user.getBirthday().toString());
//                mdv.addObject("sex","2");
                if(user.getSex()=='f')
                {
                    mdv.addObject("sex","女");
                    mdv.addObject("sex_ab","男");

                }
                else {
                    mdv.addObject("sex_ab","女");
                    mdv.addObject("sex","男");
                }
            }
        }
        else//没有输入密码，不更新，返回默认值
        {
            mdv.addObject("result","至少输入旧密码以便更改信息！");
            user=uservice.userMessage(SaveUserId.userId);
            if(user!=null)//       初次登录界面给用户返回数据库原有的值
            {
                mdv.addObject("username",user.getUser_name());
                if(user.getIntroduction()!=null)
                    mdv.addObject("introduction",user.getIntroduction());
                if(user.getEmail()!=null)
                    mdv.addObject("email",user.getEmail());
                if(user.getBirthday()!=null)
                    mdv.addObject("birthday",user.getBirthday().toString());
//                mdv.addObject("sex","2");
                if(user.getSex()=='f')
                {
                    mdv.addObject("sex","女");
                    mdv.addObject("sex_ab","男");

                }
                else {
                    mdv.addObject("sex_ab","女");
                    mdv.addObject("sex","男");
                }
            }

        }
        mdv.setViewName("setting");
        return mdv;
    }
}
